<template>
  <view class="leave-applications">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <view class="nav-left" @click="goBack">
        <u-icon name="arrow-left" color="#ffffff" size="24"></u-icon>
      </view>
      <view class="nav-center">
        <text class="nav-title">我的请假</text>
      </view>
      <view class="nav-right"> </view>
    </view>

    <!-- 筛选区域 -->
    <view class="search-card">
      <view class="search-header" @click="toggleSearchExpand">
        <view class="search-header-left">
          <u-icon name="search" size="18" color="#1678ff"></u-icon>
          <text class="search-header-title">筛选条件</text>
        </view>
        <view class="search-header-right">
          <text class="expand-text">{{ searchExpanded ? '收起' : '展开' }}</text>
          <u-icon
            :name="searchExpanded ? 'arrow-up' : 'arrow-down'"
            size="16"
            color="#999"
          ></u-icon>
        </view>
      </view>

      <view class="search-form" v-show="searchExpanded">
        <view class="search-row">
          <view class="form-item" @click="statusPickerVisible = true">
            <text class="label">状态</text>
            <text class="value" :class="{ placeholder: !searchForm.currentStatus }">
              {{ currentStatusLabel }}
            </text>
            <u-icon name="arrow-down" color="#909399" size="16" />
          </view>
          <view class="form-item">
            <text class="label">提交时间</text>
            <uni-datetime-picker
              v-model="dateRange"
              type="daterange"
              rangeSeparator="至"
              @change="handleDateChange"
            />
          </view>
        </view>
        <view class="search-actions">
          <u-button type="primary" size="small" @click="handleSearch">搜索</u-button>
          <u-button size="small" @click="handleReset">重置</u-button>
        </view>
      </view>
    </view>

    <!-- 列表区域 -->
    <view class="list-card">
      <view v-if="loading" class="loading-box">
        <u-loading-icon size="28" text="加载中..." />
      </view>

      <view v-else>
        <view v-if="tableData.length" class="leave-list">
          <view class="leave-item" v-for="item in tableData" :key="item.id">
            <view class="item-header">
              <view class="title-block">
                <text class="title">{{ item.reason || '请假申请' }}</text>
                <text class="subtitle" v-if="item.location">地点：{{ item.location }}</text>
              </view>
              <u-tag
                :text="getStatusLabel(item.currentStatus)"
                :type="getStatusTagType(item.currentStatus)"
                size="mini"
                plain
              />
            </view>

            <view class="item-body">
              <view class="info-row">
                <text class="info-label">申请人</text>
                <text class="info-value">{{ item.applicantName || '-' }}</text>
              </view>
              <view class="info-row">
                <text class="info-label">时段</text>
                <text class="info-value">
                  {{ formatDateRange(item.startTime, item.endTime) }}
                </text>
              </view>
              <!-- <view class="info-row">
                <text class="info-label">天数</text>
                <text class="info-value">{{ item.totalDays ?? '-' }}</text>
              </view> -->
              <view class="info-row">
                <text class="info-label">当前步骤</text>
                <text class="info-value">{{ item.currentStep || '待发起' }}</text>
              </view>
              <view class="info-row" v-if="item.nextStepName">
                <text class="info-label">下一步骤</text>
                <text class="info-value">{{ item.nextStepName || '-' }}</text>
              </view>
              <view class="info-row">
                <text class="info-label">当前处理人</text>
                <text class="info-value">{{ item.currentApproverName || '-' }}</text>
              </view>
              <view class="info-row">
                <text class="info-label">提交时间</text>
                <text class="info-value">{{ formatDate(item.submitTime) || '-' }}</text>
              </view>
            </view>

            <view class="item-footer">
              <view class="actions">
                <u-button size="mini" type="primary" plain @click.stop="handleView(item)">
                  查看
                </u-button>
                <u-button
                  v-if="canEdit(item)"
                  size="mini"
                  type="warning"
                  plain
                  @click.stop="handleEdit(item)"
                >
                  编辑
                </u-button>
                <u-button
                  v-if="canEdit(item)"
                  size="mini"
                  type="success"
                  plain
                  @click.stop="handleSubmitDraft(item)"
                >
                  提交
                </u-button>
                <u-button
                  v-if="canEdit(item)"
                  size="mini"
                  type="error"
                  plain
                  @click.stop="handleDelete(item)"
                >
                  删除
                </u-button>
              </view>
            </view>
          </view>
        </view>
        <u-empty v-else mode="list" text="暂无请假申请" />
      </view>

      <view v-if="pagination.total > pagination.size" class="pagination-wrapper">
        <u-pagination
          v-model="pagination.current"
          :page-size="pagination.size"
          :total="pagination.total"
          @change="handlePageChange"
        />
      </view>
    </view>
  </view>
  <!-- 状态选择弹窗 -->
  <u-popup
    :show="statusPickerVisible"
    mode="bottom"
    @close="statusPickerVisible = false"
    :closeable="true"
  >
    <view class="status-popup">
      <view
        class="status-option"
        v-for="option in statusOptions"
        :key="option.value || 'all'"
        :class="{ active: searchForm.currentStatus === option.value }"
        @click="selectStatus(option.value)"
      >
        {{ option.label }}
      </view>
    </view>
  </u-popup>

  <!-- 模板选择弹窗 -->
  <u-popup
    :show="templatePopupVisible"
    mode="center"
    borderRadius="16"
    @close="templatePopupVisible = false"
  >
    <view class="template-popup">
      <view class="popup-title">选择报备类型</view>
      <view class="template-grid">
        <view
          v-for="template in templateOptions"
          :key="template.id"
          class="template-card"
          @click="handleSelectTemplate(template)"
        >
          <text class="template-name">{{ template.templateName }}</text>
          <text class="template-desc">{{ template.description || '点击选择此类型' }}</text>
        </view>
      </view>
      <u-button size="small" text="取消" @click="templatePopupVisible = false" />
    </view>
  </u-popup>

  <!-- 审批人选择弹窗 -->
  <u-popup
    :show="approverPopupVisible"
    mode="bottom"
    :closeable="true"
    @close="handleApproverCancel"
    :safeAreaInsetBottom="true"
  >
    <view class="approver-popup">
      <view class="popup-header">
        <text class="popup-title">{{ approverPopupTitle }}</text>
      </view>

      <scroll-view scroll-y class="approver-content">
        <!-- 提示信息 -->
        <view class="approver-tip" v-if="approverPreview">
          <text v-if="!approverPreview.needsSelection">
            单人审批：系统已自动选择审批人员，无需手动选择
          </text>
          <text v-else> 请选择审批人员，下方为可选人员列表 </text>
        </view>

        <!-- 搜索框 -->
        <view class="approver-search" v-if="approverOptions.length > 3">
          <u-input
            v-model="approverSearchKeyword"
            placeholder="搜索审批人"
            :clearable="true"
            prefixIcon="search"
          />
        </view>

        <!-- 可选审批人员列表 -->
        <view class="approver-list">
          <view class="list-header">
            <text class="list-title">可选审批人员</text>
            <text class="list-count">({{ filteredApproverOptions.length }})</text>
          </view>
          <scroll-view scroll-y class="list-content">
            <view
              v-for="option in filteredApproverOptions"
              :key="option.userId"
              class="approver-item"
              :class="{ selected: selectedApprovers.includes(option.userId) }"
              @click="selectApprover(option.userId)"
            >
              <view class="approver-info">
                <text class="approver-name">{{ option.userName }}</text>
                <text class="approver-desc">
                  {{ option.jobTitle || '未分配职务' }}
                  <text v-if="option.deptName"> · {{ option.deptName }}</text>
                </text>
              </view>
              <u-icon
                v-if="selectedApprovers.includes(option.userId)"
                name="checkmark"
                color="#2979ff"
                size="20"
              />
            </view>
            <u-empty v-if="filteredApproverOptions.length === 0" mode="list" text="暂无匹配人员" />
          </scroll-view>
        </view>

        <!-- 已选审批人员列表 -->
        <view class="approver-list selected-list" v-if="selectedApprovers.length > 0">
          <view class="list-header">
            <text class="list-title">已选审批人员</text>
            <text class="list-count">({{ selectedApprovers.length }})</text>
          </view>
          <scroll-view scroll-y class="list-content">
            <view
              v-for="(approverId, index) in selectedApprovers"
              :key="approverId"
              class="approver-item selected-item"
            >
              <view class="order-number">{{ index + 1 }}</view>
              <view class="approver-info">
                <text class="approver-name">
                  {{ getApproverById(approverId)?.userName || '未知' }}
                </text>
                <text class="approver-desc">
                  {{ getApproverById(approverId)?.jobTitle || '未分配职务' }}
                  <text v-if="getApproverById(approverId)?.deptName">
                    · {{ getApproverById(approverId)?.deptName }}
                  </text>
                </text>
              </view>
              <view class="remove-icon" @click.stop="removeApprover(approverId)">
                <u-icon name="close" color="#909399" size="18" />
              </view>
            </view>
          </scroll-view>
        </view>

        <!-- 审批意见 -->
        <!-- <view class="approval-form">
          <view class="form-label">审批意见 *</view>
          <u-textarea
            v-model="approvalOpinion"
            placeholder="请输入审批意见"
            :maxlength="500"
            :count="true"
            height="120"
          />
        </view> -->
      </scroll-view>

      <!-- 底部按钮 -->
      <view class="popup-footer">
        <u-button type="info" plain @click="handleApproverCancel" :disabled="approverSubmitting">
          取消
        </u-button>
        <u-button
          type="primary"
          @click="handleApproverConfirm"
          :loading="approverSubmitting"
          :disabled="!approvalOpinion.trim()"
        >
          确认提交
        </u-button>
      </view>
    </view>
  </u-popup>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import {
  getEnabledLeaveTemplates,
  getMyLeaveApplications,
  deleteLeaveApplication,
  submitLeaveApplication,
  previewLeaveApplicationNextStep,
  type LeaveApplicationDetail,
  type LeaveTemplateSimple,
  type LeaveApplicationNextStepPreview,
  type LeaveApplicationApproverOption,
} from '@/Api/leave'
import { UserManager } from '@/utils/user'

const loading = ref(false)
const tableData = ref<LeaveApplicationDetail[]>([])
const dateRange = ref<string[]>([])
const searchExpanded = ref(false)
const statusPickerVisible = ref(false)
const templatePopupVisible = ref(false)
const approverPopupVisible = ref(false)
const approverSubmitting = ref(false)
const pendingSubmitRow = ref<LeaveApplicationDetail | null>(null)
const approverPreview = ref<LeaveApplicationNextStepPreview | null>(null)
const approverOptions = ref<LeaveApplicationApproverOption[]>([])
const selectedApprovers = ref<number[]>([])
const approvalOpinion = ref('-')
const approverSearchKeyword = ref('')

// 审批人弹窗标题（根据用户类型动态显示）
const approverPopupTitle = computed(() => {
  const userInfo = UserManager.getFullUserInfo()
  const externalFlag = Number(userInfo?.externalLiaison ?? 0)
  const isExternalUser = externalFlag === 1
  return isExternalUser ? '选择单位负责人' : '选择科室负责人'
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
})

const searchForm = reactive({
  currentStatus: '',
  submitStartTime: '',
  submitEndTime: '',
})

const statusOptions = [
  { label: '全部状态', value: '' },
  { label: '草稿', value: 'draft' },
  { label: '审批中', value: 'pending' },
  { label: '已通过', value: 'approved' },
  { label: '已驳回', value: 'rejected' },
  { label: '已撤销', value: 'cancelled' },
]

const templateOptions = ref<LeaveTemplateSimple[]>([])
const currentUserId = computed(() => UserManager.getFullUserInfo()?.id || null)

const currentStatusLabel = computed(() => {
  const found = statusOptions.find((item) => item.value === searchForm.currentStatus)
  return found?.label || '全部状态'
})

const hasLoaded = ref(false)

// 返回上一页
const goBack = () => {
  const pages = getCurrentPages()
  // 如果页面栈只有1个页面，说明无法返回，直接跳转到首页
  if (pages.length <= 1) {
    uni.reLaunch({
      url: '/pages/index/index',
    })
  } else {
    // 有多个页面，执行返回操作
    uni.navigateBack({
      delta: 1,
    })
  }
}

const loadTableData = async () => {
  if (!currentUserId.value) {
    await UserManager.ensureUserInfo()
  }
  const userId = currentUserId.value
  if (!userId) {
    uni.showToast({ title: '未获取到用户信息', icon: 'none' })
    return
  }

  try {
    loading.value = true
    const response: any = await getMyLeaveApplications(
      Number(userId),
      searchForm.currentStatus || undefined,
      pagination.current,
      pagination.size,
      searchForm.submitStartTime || undefined,
      searchForm.submitEndTime || undefined,
    )
    const body = response?.data || response
    const list = body?.data?.records || body?.records || []
    const total = body?.data?.total ?? body?.total ?? list.length

    tableData.value = list
    pagination.total = total
  } catch (error) {
    console.error('加载请假申请失败:', error)
    uni.showToast({ title: '加载数据失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

const loadTemplateOptions = async () => {
  try {
    const res: any = await getEnabledLeaveTemplates()
    const body = res?.data || res
    templateOptions.value = body?.data || body || []
  } catch (error) {
    console.error('加载模板列表失败:', error)
  }
}

const handleDateChange = (value: string[]) => {
  if (Array.isArray(value) && value.length === 2) {
    searchForm.submitStartTime = `${value[0]} 00:00:00`
    searchForm.submitEndTime = `${value[1]} 23:59:59`
  } else {
    searchForm.submitStartTime = ''
    searchForm.submitEndTime = ''
  }
}

// 切换搜索展开/收起
const toggleSearchExpand = () => {
  searchExpanded.value = !searchExpanded.value
}

const handleSearch = () => {
  pagination.current = 1
  loadTableData()
}

const handleReset = () => {
  searchForm.currentStatus = ''
  searchForm.submitStartTime = ''
  searchForm.submitEndTime = ''
  dateRange.value = []
  pagination.current = 1
  loadTableData()
}

const handlePageChange = (page: number) => {
  pagination.current = page
  loadTableData()
}

const selectStatus = (value?: string) => {
  searchForm.currentStatus = value || ''
  statusPickerVisible.value = false
}

const formatDateTime = (value?: string) => {
  if (!value) return '-'
  return value.replace('T', ' ').substring(0, 16)
}

const formatDate = (value?: string) => {
  if (!value) return '-'
  // 提取日期部分（YYYY-MM-DD），忽略时间部分
  return value.substring(0, 10)
}

const formatDateRange = (start?: string, end?: string) => {
  if (!start || !end) return '-'
  return `${formatDateTime(start)} 至 ${formatDateTime(end)}`
}

const getStatusTagType = (status?: string) => {
  const map: Record<string, 'info' | 'warning' | 'success' | 'error'> = {
    draft: 'info',
    pending: 'warning',
    approved: 'success',
    rejected: 'error',
    cancelled: 'info',
  }
  return map[status || ''] || 'info'
}

const getStatusLabel = (status?: string) => {
  const map: Record<string, string> = {
    draft: '草稿',
    pending: '审批中',
    approved: '已通过',
    rejected: '已驳回',
    cancelled: '已撤销',
  }
  return map[status || ''] || '未知状态'
}

const canEdit = (item: LeaveApplicationDetail) => {
  return ['draft', 'rejected'].includes(item.currentStatus || '')
}

const handleCreate = async () => {
  if (!templateOptions.value.length) {
    await loadTemplateOptions()
  }

  if (!templateOptions.value.length) {
    uni.showToast({ title: '暂无可用模板', icon: 'none' })
    return
  }

  // 根据用户的 externalLiaison 字段自动选择模板
  const userInfo = UserManager.getFullUserInfo()
  const externalFlag = Number(userInfo?.externalLiaison ?? 0)
  const isExternalUser = externalFlag === 1

  console.log('🔍 用户信息:', {
    externalLiaison: userInfo?.externalLiaison,
    externalFlag,
    isExternalUser,
    userName: userInfo?.name,
  })

  console.log('📋 可用模板列表:', templateOptions.value)

  // 查找适合当前用户的模板
  const findTemplateForUser = (isExternal: boolean) => {
    // 1. 优先根据 templateCode 查找
    const preferredCode = isExternal ? 'leave_report' : 'outing_report'
    console.log(
      `🎯 查找模板，用户类型: ${isExternal ? '外部单位' : '内部人员'}，优先Code: ${preferredCode}`,
    )

    const preferredTemplate = templateOptions.value.find(
      (item) => (item as any).templateCode === preferredCode,
    )
    if (preferredTemplate) {
      console.log('✅ 根据 templateCode 找到模板:', preferredTemplate)
      return preferredTemplate
    }

    // 2. 根据关键词查找
    const keywords = isExternal
      ? ['外出', '外部', '对外', '单位']
      : ['内部', '报备', '卫健委', '人员']
    console.log('🔎 根据关键词查找:', keywords)

    const keywordTemplate = templateOptions.value.find((item) => {
      const name = item.templateName || ''
      const description = item.description || ''
      return keywords.some((keyword) => name.includes(keyword) || description.includes(keyword))
    })
    if (keywordTemplate) {
      console.log('✅ 根据关键词找到模板:', keywordTemplate)
      return keywordTemplate
    }

    // 3. 返回第一个模板
    console.log('⚠️ 未找到匹配模板，使用第一个:', templateOptions.value[0])
    return templateOptions.value[0]
  }

  const targetTemplate = findTemplateForUser(isExternalUser)
  console.log('🎯 最终选择的模板:', targetTemplate)

  // 如果只有一个模板，直接打开
  if (templateOptions.value.length === 1) {
    console.log('📝 只有一个模板，直接打开')
    handleSelectTemplate(targetTemplate)
    return
  }

  // 如果找到了匹配的模板，直接打开
  if (targetTemplate) {
    console.log('📝 找到匹配模板，直接打开')
    handleSelectTemplate(targetTemplate)
    return
  }

  // 否则显示选择弹窗
  console.log('📝 显示模板选择弹窗')
  templatePopupVisible.value = true
}

const buildQueryString = (params: Record<string, any>) => {
  return Object.entries(params)
    .filter(([, value]) => value !== undefined && value !== null && value !== '')
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
    .join('&')
}

const openFormPage = (params: Record<string, any>) => {
  const query = buildQueryString(params)
  uni.navigateTo({
    url: `/pages/leave/forms/index${query ? `?${query}` : ''}`,
  })
}

const inferTemplateCode = (name?: string, fallback?: string) => {
  if (fallback) return fallback
  if (!name) return 'leave_report'
  // 内部人员
  if (name.includes('内部')) return 'outing_report'
  // 外部人员
  return 'leave_report'
}

const handleSelectTemplate = (template: LeaveTemplateSimple) => {
  templatePopupVisible.value = false
  openFormPage({
    templateId: template.id,
    templateCode: (template as any).templateCode || inferTemplateCode(template.templateName),
    templateName: template.templateName,
    mode: 'create',
  })
}

const handleView = (row: LeaveApplicationDetail) => {
  openFormPage({
    templateId: row.flowTemplateId,
    templateName: row.flowTemplateName,
    leaveId: row.id,
    templateCode: (row as any)?.flowTemplateCode || inferTemplateCode(row.flowTemplateName),
    mode: 'view',
  })
}

const handleEdit = (row: LeaveApplicationDetail) => {
  openFormPage({
    templateId: row.flowTemplateId,
    templateName: row.flowTemplateName,
    leaveId: row.id,
    templateCode: (row as any)?.flowTemplateCode || inferTemplateCode(row.flowTemplateName),
    mode: 'edit',
  })
}

const handleSubmitDraft = async (row: LeaveApplicationDetail) => {
  try {
    const userInfo = UserManager.getFullUserInfo()
    const operatorId = userInfo?.id || 0
    if (!operatorId) {
      uni.showToast({ title: '未获取到用户信息', icon: 'none' })
      return
    }

    // 预览下一步骤
    const previewResponse: any = await previewLeaveApplicationNextStep({
      leaveId: row.id,
      operatorId,
      currentStepOrder: row.currentStepOrder ?? null,
      currentStepName: row.currentStep ?? null,
      nextStepName: row.nextStepName ?? null,
    })

    const previewBody = previewResponse?.data || previewResponse
    const previewData = (previewBody?.data || previewBody) as
      | LeaveApplicationNextStepPreview
      | undefined

    if (!previewData) {
      throw new Error(previewBody?.message || '预检失败')
    }

    const shouldSelectApprover =
      previewData.needsSelection ||
      (previewData.approverOptions && previewData.approverOptions.length > 0)

    if (shouldSelectApprover) {
      if (!previewData.approverOptions || previewData.approverOptions.length === 0) {
        uni.showToast({
          title: '未找到可选审批人，请联系管理员配置审批角色',
          icon: 'none',
        })
        return
      }
      approverOptions.value = previewData.approverOptions
      // 如果只有一个人，自动选择
      if (previewData.approverOptions.length === 1) {
        selectedApprovers.value = [previewData.approverOptions[0].userId]
      } else {
        selectedApprovers.value = []
      }
      approverPreview.value = previewData
      pendingSubmitRow.value = row
      approvalOpinion.value = '-'
      approverSearchKeyword.value = ''
      approverPopupVisible.value = true
      return
    }

    // 不需要选人，直接提交
    await submitLeaveAndRefresh(row, [], previewData)
  } catch (error: any) {
    console.error('提交失败:', error)
    uni.showToast({
      title: error?.message || '提交失败',
      icon: 'none',
    })
  }
}

const submitLeaveAndRefresh = async (
  row: LeaveApplicationDetail,
  approvers?: LeaveApplicationApproverOption[],
  preview?: LeaveApplicationNextStepPreview,
) => {
  try {
    const userInfo = UserManager.getFullUserInfo()
    const applicantId = userInfo?.id || 0
    if (!applicantId) {
      throw new Error('未获取到用户信息')
    }

    const targetStepOrder =
      preview?.nextStepOrder ??
      (typeof row.currentStepOrder === 'number' ? row.currentStepOrder + 1 : null)
    const targetStepName = preview?.nextStepName ?? null

    const selectedApproverList =
      approvers?.map((approver) => ({
        approverId: approver.userId,
        approverName: approver.userName,
        deptName: approver.deptName || approver.jobTitle || '',
        stepOrder: targetStepOrder,
        stepName: targetStepName,
      })) ?? []

    const res: any = await submitLeaveApplication({
      id: row.id,
      applicantId,
      targetStepOrder,
      targetStepName,
      action: 'approve',
      opinion: approvalOpinion.value || '-',
      selectedApprovers: selectedApproverList,
    })

    const body = res?.data || res
    if (body?.code && body.code !== 200) {
      throw new Error(body?.message || '提交失败')
    }

    uni.showToast({ title: '提交成功', icon: 'success' })
    approverPopupVisible.value = false
    resetApproverDialog()
    loadTableData()
  } catch (error: any) {
    console.error('提交失败:', error)
    throw error
  }
}

const selectApprover = (approverId: number) => {
  if (!selectedApprovers.value.includes(approverId)) {
    selectedApprovers.value.push(approverId)
  }
}

const removeApprover = (approverId: number) => {
  console.log('[removeApprover] 移除审批人:', approverId, '当前已选:', selectedApprovers.value)
  selectedApprovers.value = selectedApprovers.value.filter((id) => id !== approverId)
  console.log('[removeApprover] 移除后:', selectedApprovers.value)
}

const getApproverById = (approverId: number): LeaveApplicationApproverOption | undefined => {
  return approverOptions.value.find((item) => item.userId === approverId)
}

const filteredApproverOptions = computed(() => {
  if (!approverSearchKeyword.value.trim()) {
    return approverOptions.value
  }
  const keyword = approverSearchKeyword.value.toLowerCase()
  return approverOptions.value.filter(
    (option) =>
      option.userName.toLowerCase().includes(keyword) ||
      option.jobTitle?.toLowerCase().includes(keyword) ||
      option.deptName?.toLowerCase().includes(keyword),
  )
})

const handleApproverConfirm = async () => {
  if (!pendingSubmitRow.value || !approverPreview.value) {
    approverPopupVisible.value = false
    return
  }

  // 如果未选择审批人，提示确认是否跳过
  if (selectedApprovers.value.length === 0) {
    uni.showToast({ title: '请选择审批人员！', icon: 'none' })
    return
  }

  // 验证审批意见
  if (!approvalOpinion.value.trim()) {
    uni.showToast({ title: '请输入审批意见', icon: 'none' })
    return
  }

  try {
    approverSubmitting.value = true

    // 获取选中的审批人列表
    const selectedApproverList = selectedApprovers.value
      .map((id) => getApproverById(id))
      .filter((item): item is LeaveApplicationApproverOption => item !== undefined)

    await submitLeaveAndRefresh(pendingSubmitRow.value, selectedApproverList, approverPreview.value)
  } catch (error: any) {
    uni.showToast({
      title: error?.message || '提交失败',
      icon: 'none',
    })
  } finally {
    approverSubmitting.value = false
  }
}

const handleApproverCancel = () => {
  approverPopupVisible.value = false
  resetApproverDialog()
}

const resetApproverDialog = () => {
  pendingSubmitRow.value = null
  approverPreview.value = null
  approverOptions.value = []
  selectedApprovers.value = []
  approvalOpinion.value = '-'
  approverSearchKeyword.value = ''
}

const handleDelete = (row: LeaveApplicationDetail) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该请假申请吗？',
    success: async (res) => {
      if (!res.confirm) return
      try {
        await deleteLeaveApplication(row.id, currentUserId.value || 0)
        uni.showToast({ title: '删除成功', icon: 'success' })
        loadTableData()
      } catch (error) {
        console.error('删除失败:', error)
        uni.showToast({ title: '删除失败', icon: 'none' })
      }
    },
  })
}

onShow(async () => {
  await UserManager.ensureUserInfo()
  if (hasLoaded.value) {
    loadTableData()
  } else {
    hasLoaded.value = true
    loadTableData()
  }
})
</script>

<style scoped lang="scss">
.leave-applications {
  height: 100vh;
  background: #f5f6fa;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  /* 顶部导航 */
  .nav-header {
    background: #818cf8;
    padding: 46px 32rpx 20rpx 32rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: white;
    z-index: 99;

    .nav-left {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      .back-icon {
        font-size: 40rpx;
        font-weight: bold;
      }
    }

    .nav-center {
      flex: 1;
      text-align: center;

      .nav-title {
        font-size: 36rpx;
        font-weight: bold;
      }
    }

    .nav-right {
      min-width: 22px;
      .save-btn {
        font-size: 28rpx;
        padding: 12rpx 24rpx;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 12rpx;
      }
    }
  }

  .search-card {
    background: #fff;
    border-radius: 24rpx;
    padding: 0;
    margin: 24rpx;
    box-shadow: 0 10rpx 30rpx rgba(15, 35, 95, 0.08);
    overflow: hidden;
  }

  .search-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 28rpx;
    cursor: pointer;
    transition: background 0.3s;

    &:active {
      background: #f8f9fa;
    }

    .search-header-left {
      display: flex;
      align-items: center;

      > *:not(:last-child) {
        margin-right: 12rpx;
      }

      .search-header-title {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
      }
    }

    .search-header-right {
      display: flex;
      align-items: center;

      > *:not(:last-child) {
        margin-right: 8rpx;
      }

      .expand-text {
        font-size: 26rpx;
        color: #999;
      }
    }
  }

  .search-form {
    display: flex;
    flex-direction: column;
    padding: 0 28rpx 24rpx;
    border-top: 1rpx solid #f0f0f0;
  }

  .list-card {
    background: #f5f6fa;
    border-radius: 0;
    padding: 0 24rpx 24rpx;
    box-shadow: none;
    flex: 1;
    overflow: auto;
  }

  .search-row {
    display: flex;
    flex-direction: column;

    .form-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 16rpx 0;
      border-bottom: 1rpx solid #f0f2f5;

      &:last-child {
        border-bottom: none;
      }

      .label {
        font-size: 28rpx;
        color: #606266;
        font-weight: 500;
        margin-right: 16rpx;
      }

      .value {
        font-size: 28rpx;
        color: #303133;
      }

      .placeholder {
        color: #c0c4cc;
      }
    }
  }

  .search-actions {
    display: flex;
    justify-content: flex-end;

    > *:not(:last-child) {
      margin-right: 16rpx;
    }

    :deep(.u-button) {
      min-width: 120rpx;
      height: 64rpx;
      font-size: 26rpx;
      border-radius: 8rpx;

      &:after {
        display: none;
      }
    }
  }

  .loading-box {
    padding: 80rpx 0;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .leave-list {
    display: flex;
    flex-direction: column;

    .leave-item {
      border: none;
      border-radius: 24rpx;
      padding: 32rpx;
      background: #ffffff;
      box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
      margin-bottom: 24rpx;
      transition: all 0.3s ease;
      position: relative;
      overflow: hidden;

      &:active {
        transform: translateY(-2rpx);
        box-shadow: 0 6rpx 24rpx rgba(0, 0, 0, 0.12);
      }

      .item-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-top: 6rpx;
        margin-bottom: 24rpx;
        padding-bottom: 20rpx;
        border-bottom: 1rpx solid #f0f2f5;

        .title-block {
          flex: 1;
          min-width: 0;
          display: flex;
          flex-direction: column;

          > *:not(:last-child) {
            margin-bottom: 6rpx;
          }

          .title {
            font-size: 34rpx;
            color: #1f2a56;
            font-weight: 700;
            line-height: 1.4;
            word-break: break-all;
          }

          .subtitle {
            font-size: 24rpx;
            color: #909399;
            line-height: 1.4;
          }
        }
      }

      .item-body {
        display: flex;
        flex-direction: column;
        margin-bottom: 24rpx;

        > *:not(:last-child) {
          margin-bottom: 16rpx;
        }

        .info-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 28rpx;
          line-height: 1.6;

          .info-label {
            color: #606266;
            font-weight: 500;
            min-width: 140rpx;
          }

          .info-value {
            color: #303133;
            font-weight: 500;
            text-align: right;
            flex: 1;
            word-break: break-all;
          }
        }
      }

      .item-footer {
        padding-top: 20rpx;
        border-top: 1rpx solid #f0f2f5;

        .actions {
          display: flex;
          justify-content: space-around;

          > *:not(:last-child) {
            margin-right: 16rpx;
          }

          :deep(.u-button) {
            min-width: 120rpx;
            height: 64rpx;
            font-size: 26rpx;
            border-radius: 8rpx;

            &:after {
              display: none;
            }
          }
        }
      }
    }
  }

  .pagination-wrapper {
    margin-top: 16rpx;
    display: flex;
    justify-content: center;
  }
}

.status-popup {
  padding: 32rpx;

  .status-option {
    padding: 24rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    font-size: 30rpx;
    color: #303133;

    &.active {
      color: #2979ff;
      font-weight: 600;
    }

    &:last-child {
      border-bottom: none;
    }
  }
}

.template-popup {
  width: 640rpx;
  padding: 32rpx;
  text-align: center;

  .popup-title {
    font-size: 32rpx;
    font-weight: 600;
    margin-bottom: 24rpx;
  }

  .template-grid {
    display: flex;
    flex-direction: column;
    margin-bottom: 16rpx;

    > *:not(:last-child) {
      margin-bottom: 16rpx;
    }
  }

  .template-card {
    border: 1rpx solid #e4e7ed;
    border-radius: 16rpx;
    padding: 20rpx;
    text-align: left;
    background: #f9fbff;

    .template-name {
      font-size: 28rpx;
      font-weight: 600;
      color: #303133;
    }

    .template-desc {
      display: block;
      margin-top: 8rpx;
      font-size: 24rpx;
      color: #909399;
    }
  }
}

.approver-popup {
  height: 80vh;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;

  .popup-header {
    padding: 32rpx;
    border-bottom: 1rpx solid #f0f2f5;

    .popup-title {
      font-size: 36rpx;
      font-weight: 700;
      color: #1f2a56;
    }
  }

  .approver-content {
    flex: 1;
    overflow-y: auto;
    padding: 24rpx 32rpx;
  }

  .approver-tip {
    padding: 20rpx;
    background: #f0f9ff;
    border-radius: 12rpx;
    margin-bottom: 24rpx;
    font-size: 26rpx;
    color: #2979ff;
    line-height: 1.6;
  }

  .approver-search {
    margin-bottom: 24rpx;
    border: 1rpx solid #e4e7ed;
    border-radius: 12rpx;
    background: #fafbfc;
  }

  .approver-list {
    margin-bottom: 24rpx;

    &.selected-list {
      margin-top: 24rpx;
      padding-top: 24rpx;
      border-top: 1rpx solid #f0f2f5;
    }

    .list-header {
      display: flex;
      align-items: center;
      margin-bottom: 16rpx;

      > *:not(:last-child) {
        margin-right: 12rpx;
      }

      .list-title {
        font-size: 30rpx;
        font-weight: 600;
        color: #303133;
      }

      .list-count {
        font-size: 24rpx;
        color: #909399;
      }
    }

    .list-content {
      height: 480rpx;
      border: 1rpx solid #e4e7ed;
      border-radius: 12rpx;
      background: #fafbfc;
    }
  }

  .approver-item {
    display: flex;
    align-items: center;
    padding: 20rpx 24rpx;
    border-bottom: 1rpx solid #f0f2f5;
    background: #fff;
    transition: background 0.2s;

    &:last-child {
      border-bottom: none;
    }

    &:active {
      background: #f5f7fa;
    }

    &.selected {
      background: #f0f9ff;
    }

    &.selected-item {
      background: #f9fbff;
    }

    .order-number {
      width: 48rpx;
      height: 48rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(135deg, #2979ff 0%, #1e88e5 100%);
      color: #fff;
      border-radius: 50%;
      font-size: 24rpx;
      font-weight: 600;
      margin-right: 16rpx;
      flex-shrink: 0;
    }

    .approver-info {
      flex: 1;
      min-width: 0;

      .approver-name {
        display: block;
        font-size: 30rpx;
        font-weight: 600;
        color: #303133;
        margin-bottom: 6rpx;
      }

      .approver-desc {
        display: block;
        font-size: 24rpx;
        color: #909399;
        line-height: 1.4;
      }
    }
  }

  .approval-form {
    margin-top: 24rpx;
    padding-top: 24rpx;
    border-top: 1rpx solid #f0f2f5;

    .form-label {
      font-size: 28rpx;
      font-weight: 600;
      color: #303133;
      margin-bottom: 16rpx;
    }
  }

  .popup-footer {
    display: flex;
    padding: 24rpx 32rpx;
    border-top: 1rpx solid #f0f2f5;
    background: #fff;

    > *:not(:last-child) {
      margin-right: 16rpx;
    }

    :deep(.u-button) {
      flex: 1;
      height: 88rpx;
      font-size: 30rpx;

      &:after {
        display: none;
      }
    }
  }
}

// :deep(.u-button) {
//   flex: 1;
//   max-width: 300rpx;
//   height: 72rpx;
//   font-size: 30rpx;
//   margin-left: 32rpx;
//   margin-right: 0;

//   &:after {
//     display: none;
//   }

//   &:first-child {
//     margin-left: 0;
//   }
// }
</style>
